/*
   Copyright (c) [2023] [魔凤啸天]
   [MFUI] is licensed under Mulan PSL v2.
   You can use this software according to the terms and conditions of the Mulan PSL v2. 
   You may obtain a copy of Mulan PSL v2 at:
            http://license.coscl.org.cn/MulanPSL2 
   THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.  
   See the Mulan PSL v2 for more details.  
*/
#pragma once
#include "textbutton.hpp"
#include<vector>
namespace MFUI{
	//单行编辑 多行用TextBox 选中渲染用反色
	class TextEdit:public TextButton{
		static unsigned int startinput;
		bool righthand,dragged;
		std::string hinttext,edittext;
		std::vector<Font::TextUnit> cursor;//back为指示结束位置的 但是正常不允许访问
		size_t begincursor,endcursor,mousecursor,refcursor,lastcursor;//保证不越界
		SDL_Color rectcolor,hightlight;
		static SDL_Cursor* cursorcache;
		static unsigned int nvisit;
		float margin;
		size_t leftpoint,rightpoint;//绘制两端 每次绘制正文时更新
		static void texteditinputcallback(Window*,TextEdit*,SDL_Event*);
		static void texteditinputeditcallback(Window*,TextEdit*,SDL_Event*);
		static void texteditkeyboardcallback(Window*,TextEdit*,SDL_Event*);
		protected:
		~TextEdit()override;
		void _onfocus(Window* w)override;
		void _losefocus(Window* w)override;
		void _pressed(Window* w,SDL_FPoint p)override;
		void _released(Window* w,SDL_FPoint p)override;
		void _updatetext()override;
		void _validatecursor();
		//使用mousepoint计算并设置mousecursor
		void _calcmousecursor(float mousepoint);
		//文本内容修改后调用
		virtual void ontextchanged();

		public:
		bool enter;//默认true，禁用回车设为false

		TextEdit(const std::string& text,const std::string& hint,Font* font,int fontsize=18,
		SDL_Color textcolor={255,255,255,255},SDL_Color background={80,80,80,255},
		SDL_Color rectcolor={255,255,255,255},SDL_Color hightlight={11,45,100,255});
		//更新光标所在的位置（按下时同时更新选区）
		void mousemove(Window* w,SDL_FPoint p)override;
		void mouseentered(Window* w)override;
		void mouseexited(Window* w)override;
		void onremove(Window* w)override;
		void draw(Renderer* r,bool updatecache)override;

		//以可见字符为单位 一个字(包括汉字)算一个
		void setselected(size_t begin,size_t end);
		void getselected(std::string& out);
		void selectall();
		void clear();
		void backspace();
		void getcursor(size_t& begin,size_t& end);
		//返回插入后的尾部 超出默认插末尾 以可见字符为单位 一个字(包括汉字)算一个
		size_t insert(size_t pos,const std::string& t);
		void append(const std::string& t);
		//返回实际显示（Utf8字符）的个数
		size_t length()const;
		void getcontent(size_t begin,size_t end,std::string& out);
		//替换找到的n个字符串 返回替换个数
		size_t replace(const std::string& target,const std::string& t,size_t n);
		//返回替换后的下标 以可见字符为单位 一个字(包括汉字)算一个
		size_t replace(size_t begin,size_t end,const std::string& t);
		void sethint(const std::string& hint);
		const std::string& gethint();
	};
}